<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-minimal.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="简单的HTTP场景">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA高效网络库Okhttp3">
<meta property="og:url" content="https://gitee.com/lzx411559669/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/index.html">
<meta property="og:site_name" content="刘正星的博客">
<meta property="og:description" content="简单的HTTP场景">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581517708400-61f68b75-70a3-4226-922b-a23aebb76b2d.png#align=left&display=inline&height=1276&originHeight=1276&originWidth=2640&size=0&status=done&style=none&width=2640">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581517906064-6e6a376b-6bf8-456b-b31a-ee2c43834c60.png#align=left&display=inline&height=1230&originHeight=1230&originWidth=3310&size=0&status=done&style=none&width=3310">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581518139422-22fdd9a1-19f6-45ce-acfd-72c5b6deb436.png#align=left&display=inline&height=1080&name=image.png&originHeight=1080&originWidth=1920&size=400960&status=done&style=none&width=1920">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581518467545-c58ab58b-edbc-4e64-a494-b8b42b68d019.png#align=left&display=inline&height=528&name=image.png&originHeight=528&originWidth=743&size=79202&status=done&style=none&width=743">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581518106051-d6b91ecf-75e6-46e4-9adc-c9ba06a329f5.png#align=left&display=inline&height=1228&originHeight=1228&originWidth=3314&size=0&status=done&style=none&width=3314">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1583209110276-38fcde51-a20e-4257-89c6-8e9ae4e82485.png#align=left&display=inline&height=1047&name=image.png&originHeight=1047&originWidth=974&size=227988&status=done&style=none&width=974">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1583226987115-45b432c2-39af-4403-9443-13bc5ba00da3.png#align=left&display=inline&height=1047&name=image.png&originHeight=1047&originWidth=974&size=180838&status=done&style=none&width=974">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1583301059897-61d86485-d955-4375-a2c5-8d73a3a1c715.png#align=left&display=inline&height=875&name=image.png&originHeight=875&originWidth=1440&size=447940&status=done&style=none&width=1440">
<meta property="article:published_time" content="2020-03-04T14:15:17.000Z">
<meta property="article:modified_time" content="2020-03-04T14:32:54.582Z">
<meta property="article:author" content="刘正星">
<meta property="article:tag" content="高效网络库Okhttp3">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581517708400-61f68b75-70a3-4226-922b-a23aebb76b2d.png#align=left&display=inline&height=1276&originHeight=1276&originWidth=2640&size=0&status=done&style=none&width=2640">

<link rel="canonical" href="https://gitee.com/lzx411559669/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>JAVA高效网络库Okhttp3 | 刘正星的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="刘正星的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
<a href="https://github.com/lzx411559669" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">刘正星的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">欢迎！</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lzx411559669/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/uploads/me.jpg">
      <meta itemprop="name" content="刘正星">
      <meta itemprop="description" content="一名不知名的小菜鸡">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="刘正星的博客">
    </span>
      <header class="post-header">
         
        <h1 class="post-title" itemprop="name headline">
          JAVA高效网络库Okhttp3
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-04 22:15:17 / 修改时间：22:32:54" itemprop="dateCreated datePublished" datetime="2020-03-04T22:15:17+08:00">2020-03-04</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JAVA/" itemprop="url" rel="index"><span itemprop="name">JAVA</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>22k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>20 分钟</span>
            </span>
            <div class="post-description">简单的HTTP场景</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <meta name="referrer" content="no-referrer"/>
# JAVA高效网络库Okhttp3

<p><a name="ZyLRY"></a></p>
<h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>Netty适合开发客户端与服务端实时频繁通信的场景。<br />比较的简单的HTTP场景（如下载文件、加载图片、提交表单数据、从服务端读取一段配置信息等）<br />这些通过HTTP进行数据传输的场景适合Okhttp3<br />Okhttp3是一个非常流行的HTTP库，已取代曾经流行的Apache HttpClient 。<br /><strong>Okhttp3的优点：简单易用，性能优秀，支持HTTP/2。</strong><br /><strong>在安卓APP开发中应用也非常广泛。服务端的JAVA应用程序同样很适合。</strong><br />**<br />抓取淘宝首页:<a href="http://www.taobao.com页面内容" target="_blank" rel="noopener">http://www.taobao.com页面内容</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.youkeda.test.http;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Call;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.lang3.StringUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetPage</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> OkHttpClient okHttpClient;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">GetPage</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    okHttpClient = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getPageContentSync</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isBlank(url)) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder().url(url).build();</span><br><span class="line">    Call call = okHttpClient.newCall(request);</span><br><span class="line">    String result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      result = call.execute().body().string();</span><br><span class="line">      System.out.println(<span class="string">"call "</span> + url + <span class="string">" , content's size="</span> + result.length());</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    GetPage gt = <span class="keyword">new</span> GetPage();</span><br><span class="line">    System.out.println(gt.getPageContentSync(<span class="string">"http://www.taobao.com"</span>));  </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a name="XtsW2"></a></p>
<h1 id="Get同步请求"><a href="#Get同步请求" class="headerlink" title="Get同步请求"></a>Get同步请求</h1><p>Okhttp3特别适合做网页的爬虫。爬取网页就相当于发起一个HTTP请求，读取网页内容。<br />增加依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.squareup.okhttp3<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>okhttp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.1.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 字符串操作工具库 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.commons<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-lang3<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.9<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>完成爬虫controller：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getPageContentSync</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 参数判断，未输入参数则直接返回</span></span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isBlank(url)) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//2.定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder().url(url).build();</span><br><span class="line">    <span class="comment">//3.使用client去请求</span></span><br><span class="line">    Call call = okHttpClient.newCall(request);</span><br><span class="line">    String result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">//4.获得返回结果</span></span><br><span class="line">      result = call.execute().body().string();</span><br><span class="line">      System.out.println(<span class="string">"call "</span> + url + <span class="string">" , content's size="</span> + result.length());</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p><strong>使用Okhttp3请求一个页面，核心步骤有4步：</strong></p>
<ul>
<li><strong>new OkHttpCilent（）；</strong></li>
</ul>
<p>生成OkHttpClient实例，因为这个实例是可以复用的 ，所以定义为成员变量。这样不用每次调用方法都产生一次实例，提升性能。</p>
<ul>
<li><strong>new Request.Builder().url(url).build();</strong></li>
</ul>
<p>根据变量url定义一个request对象。</p>
<ul>
<li><strong>okHttpClient.newCall(request);</strong></li>
</ul>
<p>构建一个call对象</p>
<ul>
<li><strong>call.excute().body().string();</strong></li>
</ul>
<p>真正执行请求，将结果已字符串形式返回。<br />程序的在第四步，一直等待远程服务器返回结果（无论成功或失败），才继续执行，所以称之为同步请求。<br />缺点：效率不高，网页较多，顺序执行往往耗时较长。</p>
<p><a name="pO6AW"></a></p>
<h1 id="get-异步请求"><a href="#get-异步请求" class="headerlink" title="get 异步请求"></a>get 异步请求</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getPageContentAsync</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isBlank(url)) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> String requestUrl = url;</span><br><span class="line">    <span class="comment">//2.定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder().url(url).build();</span><br><span class="line">    <span class="comment">//3.使用client去请求</span></span><br><span class="line">    Call call = okHttpClient.newCall(request);</span><br><span class="line">    <span class="comment">//4.回调方法</span></span><br><span class="line">    call.enqueue(<span class="keyword">new</span> Callback() &#123;</span><br><span class="line">      <span class="meta">@Override</span></span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call call, IOException e)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="meta">@Override</span></span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call call, Response response)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//5.获得网络数据</span></span><br><span class="line">        String result = response.body().string();</span><br><span class="line">        System.out.println(<span class="string">"call "</span> + requestUrl + <span class="string">" , content's size="</span> + result.length());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="string">"success"</span>;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>new OkHttpCilent（）；</strong></li>
</ul>
<p>生成OkHttpClient实例，因为这个实例是可以复用的 ，所以定义为成员变量。这样不用每次调用方法都产生一次实例，提升性能。</p>
<ul>
<li><strong>new Request.Builder().url(url).build();</strong></li>
</ul>
<p>根据变量url定义一个request对象。</p>
<ul>
<li><strong>okHttpClient.newCall(request);</strong></li>
</ul>
<p>构建一个call对象</p>
<ul>
<li><strong>call.enqueue（）；</strong></li>
</ul>
<p>提交异步请求，方法参数是一个回调方法，异步请求执行完毕以后系统会自动回调，这是与同步不同的地方。</p>
<ul>
<li><strong>response.body.string();</strong></li>
</ul>
<p>字符串形式返回结果。</p>
<p>程序不必等待，可以继续执行其他任务，这里举出的例子是返回“success”结果，只是方法执行完毕，不代表真正爬取到内容。</p>
<p><a name="RsYpq"></a></p>
<h1 id="Post-提交表单数据"><a href="#Post-提交表单数据" class="headerlink" title="Post 提交表单数据"></a>Post 提交表单数据</h1><p><strong>post模式</strong>：用于写数据，即向服务器提交数据，一般表单数据保存使用POST方式比较多。</p>
<p>另一个常见的场景是查询内容，网页上搜索框和搜索输入框，点击搜索查询时是以表单方式POST到服务端的。（还要看具体服务端是否支持POST）</p>
<p><a name="GK2AI"></a></p>
<h3 id="实战：爬取北京大学的课表"><a href="#实战：爬取北京大学的课表" class="headerlink" title="实战：爬取北京大学的课表"></a>实战：爬取北京大学的课表</h3><p>打开北京大学课表搜索页：<br /><a href="http://dean.pku.edu.cn/pkudean/course/kcbzy.php?xs=011&xn=19-20&xq=1" target="_blank" rel="noopener">http://dean.pku.edu.cn/pkudean/course/kcbzy.php?xs=011&amp;xn=19-20&amp;xq=1</a><br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581517708400-61f68b75-70a3-4226-922b-a23aebb76b2d.png#align=left&display=inline&height=1276&originHeight=1276&originWidth=2640&size=0&status=done&style=none&width=2640" alt=""></p>
<p>点击元素选择器，选中下拉选择框元素。<br />可以看到，查询选项在一个form表单中。</p>
<ul>
<li>表单的action为：kcbxs.php ，表示表单提交的目标页面是：kcbxs.php</li>
<li>专业选项名称为：zy</li>
<li>年级选项名称为：nj</li>
</ul>
<p>切换到Network，这里可以看到网络请求。</p>
<p><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581517906064-6e6a376b-6bf8-456b-b31a-ee2c43834c60.png#align=left&display=inline&height=1230&originHeight=1230&originWidth=3310&size=0&status=done&style=none&width=3310" alt=""></p>
<p>手动选好专业，年级点击提交，这时在Network面饭观察网络请求。<br />在Network中选择kcbxs.php 查看详细信息。<br />Form Data：（右下角）<br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581518139422-22fdd9a1-19f6-45ce-acfd-72c5b6deb436.png#align=left&display=inline&height=1080&name=image.png&originHeight=1080&originWidth=1920&size=400960&status=done&style=none&width=1920" alt="image.png"><br />可以观察的信息有：<br />在General—&gt;Request URL 看到表单提交的具体地址。<br />可以在Form Data中看到zy和nj的值，其他表单数据项的值，是搜索页（kcbzy.php）的查询参数（xs=011&amp;xn=19-20&amp;xq=1）。<br />代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">postContentAsync</span><span class="params">(String url, Map&lt;String, String&gt; params)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (StringUtils.isBlank(url)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//post方式提交的数据</span></span><br><span class="line">  Builder builder = <span class="keyword">new</span> FormBody.Builder();</span><br><span class="line">  <span class="keyword">for</span> (String key : params.keySet()) &#123;</span><br><span class="line">    builder.add(key, params.get(key));</span><br><span class="line">  &#125;</span><br><span class="line">  FormBody formBody = builder.build();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">final</span> Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">      .url(url)</span><br><span class="line">      .post(formBody)</span><br><span class="line">      .build();</span><br><span class="line"></span><br><span class="line">  <span class="comment">//创建/Call</span></span><br><span class="line">  Call call = okHttpClient.newCall(request);</span><br><span class="line">  <span class="keyword">final</span> String requestUrl = url;</span><br><span class="line">  <span class="comment">//加入队列 异步操作</span></span><br><span class="line">  call.enqueue(<span class="keyword">new</span> Callback() &#123;</span><br><span class="line">    <span class="comment">//请求错误回调方法</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call call, IOException e)</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">"连接失败"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call call, Response response)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (response.code() == <span class="number">200</span>) &#123;</span><br><span class="line">        <span class="comment">//5.获得网络数据</span></span><br><span class="line">        String result = response.body().string();</span><br><span class="line">        System.out.println(<span class="string">"call "</span> + requestUrl + <span class="string">" , content's size="</span> + result.length());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="string">"success"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581518467545-c58ab58b-edbc-4e64-a494-b8b42b68d019.png#align=left&display=inline&height=528&name=image.png&originHeight=528&originWidth=743&size=79202&status=done&style=none&width=743" alt="image.png"><br />POST也可以同步执行，这里举了异步提交的例子而已。<br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581518106051-d6b91ecf-75e6-46e4-9adc-c9ba06a329f5.png#align=left&display=inline&height=1228&originHeight=1228&originWidth=3314&size=0&status=done&style=none&width=3314" alt=""></p>
<p><a name="RtFad"></a></p>
<h1 id="Headers"><a href="#Headers" class="headerlink" title="Headers"></a>Headers</h1><p><a name="TCK1C"></a></p>
<h4 id="传送门：HTTP-header文档"><a href="#传送门：HTTP-header文档" class="headerlink" title="传送门：HTTP header文档"></a><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers" target="_blank" rel="noopener">传送门：HTTP header文档</a></h4><p><a name="xoCz0"></a></p>
<h2 id="User-Agent"><a href="#User-Agent" class="headerlink" title="User-Agent"></a>User-Agent</h2><p><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/User-Agent" target="_blank" rel="noopener">传送门：User-Agent文档</a><br />有时候不是所有的网站API都能请求到，有些网站出于安全等各种因素考虑，会对请求进行校验，其中一个就是请求是否来自一个真实的浏览器。<br />判断是否来自真实的浏览器，需要从HTTP消息头（Headers）取得User-Agent。<br />User-Agent 是存放在 Headers 中一种数据信息。<br />作用：告诉服务器当前用户浏览器版本，类型，甚至操作系统，CPU等技术信息。<br />（header信息不是在URL里，属于隐藏数据，不可直接看到）<br />模拟一个User-Agent:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Mozilla&#x2F;5.0 (Windows NT 6.1; WOW64) AppleWebKit&#x2F;535.1 (KHTML, like Gecko) Chrome&#x2F;14.0.835.163 Safari&#x2F;535.1</span><br></pre></td></tr></table></figure>

<p>构建Request的时候调用addHeader()方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">    .url(url)</span><br><span class="line">    .addHeader(<span class="string">"User-Agent"</span>, <span class="string">""</span>)</span><br><span class="line">    .build();</span><br></pre></td></tr></table></figure>

<p>举个🌰子<br />获取豆瓣热门电影：<br />API：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">https:&#x2F;&#x2F;movie.douban.com&#x2F;j&#x2F;search_subjects?type&#x3D;movie&amp;tag&#x3D;热门&amp;page_limit&#x3D;5&amp;page_start&#x3D;0</span><br></pre></td></tr></table></figure>
<p>page_limit=5表示只查询5条数据；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSON;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Call;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Response;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ApiAsker</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 根据输入的url，读取页面内容并返回</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getContent</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// okHttpClient 实例</span></span><br><span class="line">    OkHttpClient okHttpClient = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line">    <span class="comment">// 定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(url)</span><br><span class="line">        <span class="comment">// 添加一个 header 信息</span></span><br><span class="line">        .addHeader(<span class="string">"User-Agent"</span>, <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"</span>)</span><br><span class="line">        .build();</span><br><span class="line">    <span class="comment">// 返回结果字符串</span></span><br><span class="line">    String result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 执行请求</span></span><br><span class="line">      Response response = okHttpClient.newCall(request).execute();</span><br><span class="line">      <span class="comment">// 获取响应内容</span></span><br><span class="line">      result = response.body().string();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      <span class="comment">// 抓取异常</span></span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    String url = <span class="string">"https://movie.douban.com/j/search_subjects?type=movie&amp;tag=热门&amp;page_limit=5&amp;page_start=0"</span>;</span><br><span class="line">    ApiAsker asker = <span class="keyword">new</span> ApiAsker();</span><br><span class="line">    String content = asker.getContent(url);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 解析结果</span></span><br><span class="line">    Map contentObj = JSON.parseObject(content,Map<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    List list = (List)contentObj.get(<span class="string">"subjects"</span>);</span><br><span class="line">    System.out.println(<span class="string">"电影名称："</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;list.size() ;i++ ) &#123;</span><br><span class="line">      Map film = (Map)list.get(i);</span><br><span class="line">      String title = (String)film.get(<span class="string">"title"</span>);</span><br><span class="line">      System.out.println(title);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//电影名称：</span></span><br><span class="line"><span class="comment">//1917</span></span><br><span class="line"><span class="comment">//寄生虫</span></span><br><span class="line"><span class="comment">//通灵车教</span></span><br><span class="line"><span class="comment">//关于哈利的那些事</span></span><br><span class="line"><span class="comment">//小妇人</span></span><br></pre></td></tr></table></figure>
<p>JSON数据：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"subjects"</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"rate"</span>: <span class="string">"8.5"</span>,</span><br><span class="line">      <span class="attr">"cover_x"</span>: <span class="number">3158</span>,</span><br><span class="line">      <span class="attr">"title"</span>: <span class="string">"1917"</span>,</span><br><span class="line">      <span class="attr">"url"</span>: <span class="string">"https://movie.douban.com/subject/30252495/"</span>,</span><br><span class="line">      <span class="attr">"playable"</span>: <span class="literal">false</span>,</span><br><span class="line">      <span class="attr">"cover"</span>: <span class="string">"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2570243317.webp"</span>,</span><br><span class="line">      <span class="attr">"id"</span>: <span class="string">"30252495"</span>,</span><br><span class="line">      <span class="attr">"cover_y"</span>: <span class="number">5000</span>,</span><br><span class="line">      <span class="attr">"is_new"</span>: <span class="literal">false</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"rate"</span>: <span class="string">"8.7"</span>,</span><br><span class="line">      <span class="attr">"cover_x"</span>: <span class="number">1500</span>,</span><br><span class="line">      <span class="attr">"title"</span>: <span class="string">"寄生虫"</span>,</span><br><span class="line">      <span class="attr">"url"</span>: <span class="string">"https://movie.douban.com/subject/27010768/"</span>,</span><br><span class="line">      <span class="attr">"playable"</span>: <span class="literal">false</span>,</span><br><span class="line">      <span class="attr">"cover"</span>: <span class="string">"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2561439800.webp"</span>,</span><br><span class="line">      <span class="attr">"id"</span>: <span class="string">"27010768"</span>,</span><br><span class="line">      <span class="attr">"cover_y"</span>: <span class="number">2138</span>,</span><br><span class="line">      <span class="attr">"is_new"</span>: <span class="literal">false</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"rate"</span>: <span class="string">"6.6"</span>,</span><br><span class="line">      <span class="attr">"cover_x"</span>: <span class="number">827</span>,</span><br><span class="line">      <span class="attr">"title"</span>: <span class="string">"通灵车教"</span>,</span><br><span class="line">      <span class="attr">"url"</span>: <span class="string">"https://movie.douban.com/subject/30483355/"</span>,</span><br><span class="line">      <span class="attr">"playable"</span>: <span class="literal">false</span>,</span><br><span class="line">      <span class="attr">"cover"</span>: <span class="string">"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2562147653.webp"</span>,</span><br><span class="line">      <span class="attr">"id"</span>: <span class="string">"30483355"</span>,</span><br><span class="line">      <span class="attr">"cover_y"</span>: <span class="number">1225</span>,</span><br><span class="line">      <span class="attr">"is_new"</span>: <span class="literal">true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"rate"</span>: <span class="string">"6.4"</span>,</span><br><span class="line">      <span class="attr">"cover_x"</span>: <span class="number">750</span>,</span><br><span class="line">      <span class="attr">"title"</span>: <span class="string">"关于哈利的那些事"</span>,</span><br><span class="line">      <span class="attr">"url"</span>: <span class="string">"https://movie.douban.com/subject/34887994/"</span>,</span><br><span class="line">      <span class="attr">"playable"</span>: <span class="literal">false</span>,</span><br><span class="line">      <span class="attr">"cover"</span>: <span class="string">"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2581161597.webp"</span>,</span><br><span class="line">      <span class="attr">"id"</span>: <span class="string">"34887994"</span>,</span><br><span class="line">      <span class="attr">"cover_y"</span>: <span class="number">1108</span>,</span><br><span class="line">      <span class="attr">"is_new"</span>: <span class="literal">true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"rate"</span>: <span class="string">"8.2"</span>,</span><br><span class="line">      <span class="attr">"cover_x"</span>: <span class="number">3000</span>,</span><br><span class="line">      <span class="attr">"title"</span>: <span class="string">"小妇人"</span>,</span><br><span class="line">      <span class="attr">"url"</span>: <span class="string">"https://movie.douban.com/subject/26348103/"</span>,</span><br><span class="line">      <span class="attr">"playable"</span>: <span class="literal">false</span>,</span><br><span class="line">      <span class="attr">"cover"</span>: <span class="string">"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2575325937.webp"</span>,</span><br><span class="line">      <span class="attr">"id"</span>: <span class="string">"26348103"</span>,</span><br><span class="line">      <span class="attr">"cover_y"</span>: <span class="number">4454</span>,</span><br><span class="line">      <span class="attr">"is_new"</span>: <span class="literal">false</span></span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a name="87GZ9"></a></p>
<h2 id="Referer"><a href="#Referer" class="headerlink" title="Referer"></a>Referer</h2><p>图片防盗链：浏览器 在请求网页图片或其他文件，会自动在Headers加一个Referer信息，表示请求来源。即浏览器告诉服务器，从当前网站请求图片，图片服务器拒绝访问，（图片服务器不允许其他网站访问图片）。<br />模拟浏览器加 Referer 调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">    .url(url)</span><br><span class="line">    .addHeader(<span class="string">"Referer"</span>, <span class="string">"https://ham.youkeda.com/course/j14/3/1/0"</span>)</span><br><span class="line">    .build();</span><br></pre></td></tr></table></figure>
<p>http响应状态码403，禁止访问图片<br />解决办法：设置Referer信息为图片原始使用网站。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(url)</span><br><span class="line">        .addHeader(<span class="string">"Referer"</span>, <span class="string">"https://unreach.yuque.com"</span>)</span><br><span class="line">        .build();</span><br></pre></td></tr></table></figure>

<p>PS:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">response.request().url().toString();<span class="comment">//获取最终响应的URL（可能与原始URL不一致）</span></span><br></pre></td></tr></table></figure>
<p><a name="DUH7T"></a></p>
<h2 id="Host"><a href="#Host" class="headerlink" title="Host"></a>Host</h2><p><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Host" target="_blank" rel="noopener">传送门：Host文档</a><br />Host表示当前请求的域名，当URL中不写域名或写IP地址，设置Host就有用了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">    .url(url)</span><br><span class="line">    .addHeader(<span class="string">"Host"</span>, <span class="string">"www.douban.com"</span>)</span><br><span class="line">    .build();</span><br></pre></td></tr></table></figure>
<p>Host的值一定是一个域名且不带协议头（把headers的三个重要信息都写全可以避免很多问题）</p>
<p><a name="slcyn"></a></p>
<h1 id="下载文件，图片"><a href="#下载文件，图片" class="headerlink" title="下载文件，图片"></a>下载文件，图片</h1><p><strong>三个步骤：</strong>创建文件对象—&gt;写入内容—&gt;关闭写入操作</p>
<p><a name="WsX18"></a></p>
<h4 id="写入文本文件："><a href="#写入文本文件：" class="headerlink" title="写入文本文件："></a>写入文本文件：</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.File;</span><br><span class="line"><span class="keyword">import</span> java.io.FileWriter;</span><br><span class="line"><span class="comment">// 文件对象</span></span><br><span class="line">File file = <span class="keyword">new</span> File(<span class="string">"foo.txt"</span>);</span><br><span class="line"><span class="comment">// 写入内容</span></span><br><span class="line">FileWriter fileWritter = <span class="keyword">new</span> FileWriter(file.getName());</span><br><span class="line">fileWritter.write(content);</span><br><span class="line"><span class="comment">// 关闭</span></span><br><span class="line">fileWritter.close();</span><br></pre></td></tr></table></figure>

<p><a name="Z8Lqn"></a></p>
<h4 id="写入二进制文件："><a href="#写入二进制文件：" class="headerlink" title="写入二进制文件："></a>写入二进制文件：</h4><p>请求一个excel网址：<a href="https://style.youkeda.com/img/ham/course/py2/china-city-list.xlsx" target="_blank" rel="noopener">https://style.youkeda.com/img/ham/course/py2/china-city-list.xlsx</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Call;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Response;</span><br><span class="line"><span class="keyword">import</span> java.io.File;</span><br><span class="line"><span class="keyword">import</span> java.io.FileOutputStream;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExcelAsker</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 根据输入的url，读取页面内容并返回</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">byte</span>[] getFile(String url) &#123;</span><br><span class="line">    <span class="comment">// okHttpClient 实例</span></span><br><span class="line">    OkHttpClient okHttpClient = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line">    <span class="comment">// 定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder().url(url).build();</span><br><span class="line">    <span class="keyword">byte</span>[] bytes = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 执行请求</span></span><br><span class="line">      Response response = okHttpClient.newCall(request).execute();</span><br><span class="line">      bytes = response.body().bytes();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      <span class="comment">// 抓取异常</span></span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> bytes;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    String url = <span class="string">"https://style.youkeda.com/img/ham/course/py2/china-city-list.xlsx"</span>;</span><br><span class="line">    ExcelAsker asker = <span class="keyword">new</span> ExcelAsker();</span><br><span class="line">    <span class="keyword">byte</span>[] data = asker.getFile(url);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 文件对象</span></span><br><span class="line">      File file = <span class="keyword">new</span> File(<span class="string">"china-city-list.xlsx"</span>);  </span><br><span class="line"></span><br><span class="line">      <span class="comment">// 写文件</span></span><br><span class="line">      FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file);  </span><br><span class="line">      fos.write(data, <span class="number">0</span>, data.length);  </span><br><span class="line"></span><br><span class="line">      <span class="comment">// 必须刷新并关闭</span></span><br><span class="line">      fos.flush();  </span><br><span class="line">      fos.close();  </span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a name="cakFc"></a></p>
<h4 id="下载图片：跟二进制文件一致。"><a href="#下载图片：跟二进制文件一致。" class="headerlink" title="下载图片：跟二进制文件一致。"></a>下载图片：跟二进制文件一致。</h4><p><a name="28Hx0"></a></p>
<h4 id="解析excel"><a href="#解析excel" class="headerlink" title="解析excel"></a>解析excel</h4><p>**</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>easyexcel<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>解析路径：sheet（工作表） -&gt; 行 -&gt; 列<br />（计算机中，第一个单元格的位置是0，第一个sheet，第一行，第一列对应是0，0，0）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.alibaba.excel.EasyExcel;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="comment">// 读取第一个sheet</span></span><br><span class="line">List&lt;Map&lt;Integer, String&gt;&gt; sheetDatas = EasyExcel.read(<span class="string">"xzq_201907.xlsx"</span>).sheet(<span class="number">0</span>).doReadSync();</span><br><span class="line"><span class="comment">// List 中每个元素表示一行</span></span><br><span class="line"><span class="keyword">for</span> (Map&lt;Integer, String&gt; rowData : sheetDatas) &#123;</span><br><span class="line">  <span class="comment">// Map 中用序号指代每一列</span></span><br><span class="line">  <span class="keyword">for</span> (Integer index : rowDaforta.keySet()) &#123;nc</span><br><span class="line">    <span class="comment">// 列值</span></span><br><span class="line">    String columnValue = rowData.get(index);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>自动转换为类：</strong><br />如果知道excel文件每一列的含义，用对象表示更直观</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.alibaba.excel.EasyExcel;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="comment">// 读取第一个sheet</span></span><br><span class="line">List&lt;DemoData&gt; sheetDatas = EasyExcel.read(<span class="string">"xzq_201907.xlsx"</span>).head(DemoData<span class="class">.<span class="keyword">class</span>).<span class="title">sheet</span>(0).<span class="title">doReadSync</span>()</span>;</span><br></pre></td></tr></table></figure>
<p>这里多调用一个方法：head(DemoData.class)，DemoData就是自定义类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 属性定义的顺序必须与列顺序保持一致</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DemoData</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String code1;</span><br><span class="line">  <span class="keyword">private</span> String city1;</span><br><span class="line">  <span class="keyword">private</span> String code2;</span><br><span class="line">  <span class="keyword">private</span> String city2;</span><br><span class="line">  <span class="keyword">private</span> String code3;</span><br><span class="line">  <span class="keyword">private</span> String city3;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>🌰子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSON;</span><br><span class="line"><span class="keyword">import</span> java.io.File;</span><br><span class="line"><span class="keyword">import</span> java.io.FileOutputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Response;</span><br><span class="line"><span class="keyword">import</span> com.alibaba.excel.EasyExcel;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExcelAsker</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 根据输入的url，读取页面内容并返回</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">byte</span>[] getFile(String url) &#123;</span><br><span class="line">    <span class="comment">// okHttpClient 实例</span></span><br><span class="line">    OkHttpClient okHttpClient = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line">    <span class="comment">// 定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder().url(url).build();</span><br><span class="line">    <span class="keyword">byte</span>[] bytes = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 执行请求</span></span><br><span class="line">      Response response = okHttpClient.newCall(request).execute();</span><br><span class="line">      bytes = response.body().bytes();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      <span class="comment">// 抓取异常</span></span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> bytes;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    String url = <span class="string">"https://style.youkeda.com/img/ham/course/py2/china-city-list.xlsx"</span>;</span><br><span class="line">    ExcelAsker asker = <span class="keyword">new</span> ExcelAsker();</span><br><span class="line">    <span class="keyword">byte</span>[] data = asker.getFile(url);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      File file = <span class="keyword">new</span> File(<span class="string">"china-city-list.xlsx"</span>);</span><br><span class="line"></span><br><span class="line">      FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file);</span><br><span class="line">      fos.write(data, <span class="number">0</span>, data.length);</span><br><span class="line"></span><br><span class="line">      fos.flush();</span><br><span class="line">      fos.close();</span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">"下载成功"</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 解析 excel 文件</span></span><br><span class="line">    List&lt;Map&lt;Integer,String&gt;&gt;sheetDatas = EasyExcel.read(<span class="string">"china-city-list.xlsx"</span>).sheet(<span class="number">0</span>).doReadSync();</span><br><span class="line">    <span class="comment">//遍历每一行</span></span><br><span class="line">      <span class="keyword">for</span> (Map&lt;Integer,String&gt; item :sheetDatas )&#123;</span><br><span class="line">      <span class="keyword">for</span>(Integer index:item.keySet())&#123;</span><br><span class="line">        System.out.print(index+<span class="string">":"</span>+item.get(index)+<span class="string">" "</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      System.out.println();</span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a name="7ZbQL"></a></p>
<h1 id="cookie-amp-session"><a href="#cookie-amp-session" class="headerlink" title="cookie&amp;session"></a>cookie&amp;session</h1><p><a name="Dpyum"></a></p>
<h2 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h2><p>如果API，网页，文件需要登录才能访问，就需要用到cookie<br><a name="5MV03"></a></p>
<h3 id="1-前提"><a href="#1-前提" class="headerlink" title="1.前提"></a>1.前提</h3><p>登录网站，必须找到登录后的cookie，登录信息存放在cookie里<br><a name="QIVCJ"></a></p>
<h3 id="2-找到cookie"><a href="#2-找到cookie" class="headerlink" title="2.找到cookie"></a>2.找到cookie</h3><p><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1583209110276-38fcde51-a20e-4257-89c6-8e9ae4e82485.png#align=left&display=inline&height=1047&name=image.png&originHeight=1047&originWidth=974&size=227988&status=done&style=none&width=974" alt="image.png"></p>
<p>把cookie的值不包含（Cookie：）拷贝放入一个cookie.txt文件中<br />（cookie内容很长，经过加密处理的）<br />需要把cookie信息字符转换为 Map 类型的数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Call;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Response;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PageAsker</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 根据输入的url，读取页面内容并返回</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getContent</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// okHttpClient 实例</span></span><br><span class="line">    OkHttpClient okHttpClient = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line">    <span class="comment">// 定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(url)</span><br><span class="line">        .addHeader(<span class="string">"User-Agent"</span>, <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Referer"</span>, <span class="string">"https://www.douban.com"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Host"</span>, <span class="string">"www.douban.com"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Cookie"</span>, ReadFileTool.readContent(<span class="string">"cookie.txt"</span>))</span><br><span class="line">        .build();</span><br><span class="line">    <span class="comment">// 返回结果字符串</span></span><br><span class="line">    String result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 执行请求</span></span><br><span class="line">      Response response = okHttpClient.newCall(request).execute();</span><br><span class="line">      result = response.body().string();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    String url = <span class="string">"https://www.douban.com/mine"</span>;</span><br><span class="line">    PageAsker asker = <span class="keyword">new</span> PageAsker();</span><br><span class="line">    String content = asker.getContent(url);</span><br><span class="line"></span><br><span class="line">    System.out.println(content);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.FileReader;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 读文件工具类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ReadFileTool</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 读取指定文件的内容</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">readContent</span><span class="params">(String fileName)</span> </span>&#123;</span><br><span class="line">    FileReader fr = <span class="keyword">null</span>;</span><br><span class="line">    StringBuilder strBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      fr = <span class="keyword">new</span> FileReader(fileName);</span><br><span class="line">      <span class="keyword">int</span> ch = <span class="number">0</span>;</span><br><span class="line">      <span class="keyword">while</span> ((ch = fr.read()) != -<span class="number">1</span>) &#123;</span><br><span class="line">        strBuilder.append((<span class="keyword">char</span>) ch);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (fr != <span class="keyword">null</span>) &#123;</span><br><span class="line">          fr.close();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> strBuilder.toString();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>cookie也是放在headers中的<br />弊端：存放在客户端浏览器，且是临时的，登录后还想以登陆状态与服务器通讯比较麻烦。<br />Session对象可以解决这个问题<br><a name="KKxWO"></a></p>
<h2 id="session"><a href="#session" class="headerlink" title="session"></a>session</h2><p><a name="ZmCwl"></a></p>
<h3 id="收集信息"><a href="#收集信息" class="headerlink" title="收集信息"></a>收集信息</h3><p>时光网登陆，收集信息，打开开发者工具，勾选 Perserve log 输入账号密码登陆，在网络请求中找到登陆请求signinLogin<br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1583226987115-45b432c2-39af-4403-9443-13bc5ba00da3.png#align=left&display=inline&height=1047&name=image.png&originHeight=1047&originWidth=974&size=180838&status=done&style=none&width=974" alt="image.png"></p>
<p>需要收集关键的信息：<br /></p>
<ul>
<li>执行方式（GET/POST）</li>
<li>HOST</li>
<li>Referer</li>
<li>User-Agent</li>
<li>表单数据，数据名称和数据值</li>
<li>登陆地址（URL）<br><a name="V9Ky5"></a><h3 id="编码实现"><a href="#编码实现" class="headerlink" title="编码实现"></a>编码实现</h3></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Cookie;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> okhttp3.CookieJar;</span><br><span class="line"><span class="keyword">import</span> okhttp3.FormBody;</span><br><span class="line"><span class="keyword">import</span> okhttp3.FormBody.Builder;</span><br><span class="line"><span class="keyword">import</span> okhttp3.HttpUrl;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PageLoginer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用 CookieJar 实现 cookie 的存储，便于登录后请求其它 URL 可以复用</span></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> OkHttpClient okHttpClient = <span class="keyword">new</span> OkHttpClient.Builder()</span><br><span class="line">      .cookieJar(<span class="keyword">new</span> CookieJar() &#123;</span><br><span class="line">        <span class="comment">// 把登录完毕后的 cookie 存储下来，再次发请求的时候复用</span></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> HashMap&lt;String, List&lt;Cookie&gt;&gt; cookieStore = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveFromResponse</span><span class="params">(HttpUrl url, List&lt;Cookie&gt; cookies)</span> </span>&#123;</span><br><span class="line">          cookieStore.put(<span class="string">"mtime.com"</span>, cookies);</span><br><span class="line">          System.out.println(<span class="string">"[saveFromResponse]url.host()="</span> + url.host());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> List&lt;Cookie&gt; <span class="title">loadForRequest</span><span class="params">(HttpUrl url)</span> </span>&#123;</span><br><span class="line">          System.out.println(<span class="string">"[loadForRequest]url.host()="</span> + url.host());</span><br><span class="line">          List&lt;Cookie&gt; cookies = cookieStore.get(<span class="string">"mtime.com"</span>);</span><br><span class="line">          <span class="keyword">return</span> cookies != <span class="keyword">null</span> ? cookies : <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">      .build();</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">postContent</span><span class="params">(String url, Map&lt;String, String&gt; formData)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//post方式提交的数据</span></span><br><span class="line">    Builder builder = <span class="keyword">new</span> FormBody.Builder();</span><br><span class="line">    <span class="comment">// 放入表单数据</span></span><br><span class="line">    <span class="keyword">for</span> (String key : formData.keySet()) &#123;</span><br><span class="line">      builder.add(key, formData.get(key));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 构建 FormBody 对象</span></span><br><span class="line">    FormBody formBody = builder.build();</span><br><span class="line">    <span class="comment">// 指定 post 方式提交FormBody</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(url)</span><br><span class="line">        .post(formBody)</span><br><span class="line">        .addHeader(<span class="string">"User-Agent"</span>,</span><br><span class="line">            <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Referer"</span>,<span class="string">"https://passport.mtime.com/member/signin/?redirectUrl=http%3a%2f%2fmy.mtime.com%2fprofile%2fbasic%2f"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Host"</span>,<span class="string">"passport.mtime.com"</span>)</span><br><span class="line">        .build();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 返回结果字符串</span></span><br><span class="line">    String result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      result = okHttpClient.newCall(request).execute().body().string();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      System.out.println(<span class="string">"request "</span> + url + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 登录页面 url</span></span><br><span class="line">    String url = <span class="string">"https://passport.mtime.com/member/signinLogin"</span>;</span><br><span class="line">    <span class="comment">// 登录表单数据</span></span><br><span class="line">    Map&lt;String, String&gt; formData = <span class="keyword">new</span> HashMap();</span><br><span class="line">    formData.put(<span class="string">"loginEmailText"</span>, <span class="string">"15896168014"</span>);</span><br><span class="line">    formData.put(<span class="string">"loginPasswordText"</span>, <span class="string">"4905be37169a12b3e6722c9362fe6177"</span>);</span><br><span class="line">    formData.put(<span class="string">"isvcode"</span>, <span class="string">"true"</span>);</span><br><span class="line">    formData.put(<span class="string">"isAutoSign"</span>, <span class="string">"false"</span>);</span><br><span class="line"></span><br><span class="line">    PageLoginer asker = <span class="keyword">new</span> PageLoginer();</span><br><span class="line">    String content = asker.postContent(url, formData);</span><br><span class="line"></span><br><span class="line">    System.out.println(content);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>CookieJar 是接口 interface ，而不是类Class 代码中 new CookieJar（）｛…..｝是匿名类。<br><a name="d3tWx"></a></p>
<h2 id="复用session"><a href="#复用session" class="headerlink" title="复用session"></a>复用session</h2><p>对OkHttpClient 对象进行重构，不在定义为 postContent（）方法的变量，而是改为类变量<code>private static final OkHttpClient okHttpClient</code> ，目的就是在整个类中，使用同一个 ，目的是整个类中使用同一个OkHttpClient执行Http请求，提升效率。<br />两次请求过程类似，只是request不同，把真正执行的过程封装成一个方法：doExcute（）被postContent和getContent调用<br />请求我的商品订单页面：<a href="http://my.mtime.com/account/ecommerce/orderList/" target="_blank" rel="noopener">http://my.mtime.com/account/ecommerce/orderList/</a><br />强调：Referer表示上级页面，来源页面，不设置表示页面或图片放在浏览器中直接打开，这里可以不设置，Host一定要设置，与浏览器登陆过程保持一致。可参考请求的URL</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Cookie;</span><br><span class="line"><span class="keyword">import</span> okhttp3.CookieJar;</span><br><span class="line"><span class="keyword">import</span> okhttp3.FormBody;</span><br><span class="line"><span class="keyword">import</span> okhttp3.FormBody.Builder;</span><br><span class="line"><span class="keyword">import</span> okhttp3.HttpUrl;</span><br><span class="line"><span class="keyword">import</span> okhttp3.OkHttpClient;</span><br><span class="line"><span class="keyword">import</span> okhttp3.Request;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PageLoginer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用 CookieJar 实现 cookie 的存储，便于登录后请求其它 URL 可以复用</span></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> OkHttpClient okHttpClient = <span class="keyword">new</span> OkHttpClient.Builder()</span><br><span class="line">      .cookieJar(<span class="keyword">new</span> CookieJar() &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> HashMap&lt;String, List&lt;Cookie&gt;&gt; cookieStore = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveFromResponse</span><span class="params">(HttpUrl url, List&lt;Cookie&gt; cookies)</span> </span>&#123;</span><br><span class="line">          cookieStore.put(<span class="string">"mtime.com"</span>, cookies);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> List&lt;Cookie&gt; <span class="title">loadForRequest</span><span class="params">(HttpUrl url)</span> </span>&#123;</span><br><span class="line">          List&lt;Cookie&gt; cookies = cookieStore.get(<span class="string">"mtime.com"</span>);</span><br><span class="line">          <span class="keyword">return</span> cookies != <span class="keyword">null</span> ? cookies : <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">      .build();</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 向指定的 URL 提交数据，并返回提交后的结果</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">postContent</span><span class="params">(String url, Map&lt;String, String&gt; formData)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//post方式提交的数据</span></span><br><span class="line">    Builder builder = <span class="keyword">new</span> FormBody.Builder();</span><br><span class="line">    <span class="comment">// 放入表单数据</span></span><br><span class="line">    <span class="keyword">for</span> (String key : formData.keySet()) &#123;</span><br><span class="line">      builder.add(key, formData.get(key));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 构建 FormBody 对象</span></span><br><span class="line">    FormBody formBody = builder.build();</span><br><span class="line">    <span class="comment">// 指定 post 方式提交FormBody</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(url)</span><br><span class="line">        .post(formBody)</span><br><span class="line">        .addHeader(<span class="string">"User-Agent"</span>,</span><br><span class="line">            <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Referer"</span>,</span><br><span class="line">            <span class="string">"https://passport.mtime.com/member/signin/?redirectUrl=http%3A%2F%2Fwww.mtime.com%2F"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Host"</span>, <span class="string">"passport.mtime.com"</span>)</span><br><span class="line">        .build();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> doExcute(request);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 根据输入的url，读取页面内容并返回</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getContent</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 定义一个request</span></span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(url)</span><br><span class="line">        .addHeader(<span class="string">"User-Agent"</span>,</span><br><span class="line">            <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"</span>)</span><br><span class="line">        .addHeader(<span class="string">"Host"</span>,<span class="string">"my.mtime.com"</span>)</span><br><span class="line">        .build();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> doExcute(request);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> String <span class="title">doExcute</span><span class="params">(Request request)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 返回结果字符串</span></span><br><span class="line">    String result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      result = okHttpClient.newCall(request).execute().body().string();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">      <span class="comment">// 抓取异常</span></span><br><span class="line">      System.out.println(<span class="string">"request "</span> + request.url() + <span class="string">" error . "</span>);</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    PageLoginer asker = <span class="keyword">new</span> PageLoginer();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 完成登录</span></span><br><span class="line">    String url = <span class="string">"https://passport.mtime.com/member/signinLogin"</span>;</span><br><span class="line">    <span class="comment">// 登录表单数据</span></span><br><span class="line">    Map&lt;String, String&gt; formData = <span class="keyword">new</span> HashMap();</span><br><span class="line">    formData.put(<span class="string">"loginEmailText"</span>, <span class="string">"15896168014"</span>);</span><br><span class="line">    formData.put(<span class="string">"loginPasswordText"</span>, <span class="string">"4905be37169a12b3e6722c9362fe6177"</span>);</span><br><span class="line">    formData.put(<span class="string">"isvcode"</span>, <span class="string">"true"</span>);</span><br><span class="line">    formData.put(<span class="string">"isAutoSign"</span>, <span class="string">"false"</span>);</span><br><span class="line">    String content = asker.postContent(url, formData);</span><br><span class="line">    System.out.println(<span class="string">"login result:"</span>);</span><br><span class="line">    System.out.println(content);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 请求我的订单</span></span><br><span class="line">    String myOrderUrl = <span class="string">"http://my.mtime.com/account/ecommerce/orderList/"</span>;</span><br><span class="line">    String myOrder = asker.getContent(myOrderUrl);</span><br><span class="line">    System.out.println(<span class="string">"getContent:"</span>);</span><br><span class="line">    System.out.println(myOrder);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a name="VpqAq"></a></p>
<h3 id="知识点"><a href="#知识点" class="headerlink" title="知识点"></a>知识点</h3><ul>
<li>static表示类变量，无论new 出个多少PageLoginer对象，PageLoginer.okHttpClient都只有一个</li>
<li>final 表示okHttpClient一旦第一次 new 出对象后，不能再new新对象</li>
</ul>
<p>某面试题</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123; </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Test t1 = <span class="keyword">new</span> Test(); </span><br><span class="line">    &#123; </span><br><span class="line">        System.out.println(<span class="string">"blockA"</span>); </span><br><span class="line">    &#125; </span><br><span class="line">    <span class="keyword">static</span> &#123; </span><br><span class="line">        System.out.println(<span class="string">"blockB"</span>); </span><br><span class="line">    &#125; </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123; </span><br><span class="line">        Test t2 = <span class="keyword">new</span> Test(); </span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述代码的执行结果为              <br />答案：blockA<br />          blockB<br />          blockA <br />解析：<br />静态块：static申明，JVM加载类时执行，且仅仅执行一次。<br />构造块：类中直接用｛｝定义，每次创建对象时执行。<br />执行顺序优先级：静态块 &gt; 构造块 &gt; 构造方法<br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1583301059897-61d86485-d955-4375-a2c5-8d73a3a1c715.png#align=left&display=inline&height=875&name=image.png&originHeight=875&originWidth=1440&size=447940&status=done&style=none&width=1440" alt="image.png"><br />静态块按照申明顺序先执行 public static Test t1 = new Test();new的时候执行构造块 输出 blockA，然后执行静态块，输出blockB（仅执行一次），最后执行main 方法中的 Test t2 = new Test(); 输出blockA（依然是构造块）</p>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/vx.png" alt="刘正星 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/alipay.jpg" alt="刘正星 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

            <div class="social-item">
              <a target="_blank" class="social-link" href="/atom.xml">
                <span class="icon">
                  <i class="fa fa-rss"></i>
                </span>

                <span class="label">RSS</span>
              </a>
            </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/" rel="tag"><i class="fa fa-tag"></i> 高效网络库Okhttp3</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/03/02/MyEclipse%202017-2018%20%E5%AE%89%E8%A3%85%E4%B8%8E%E7%A0%B4%E8%A7%A3%E6%95%99%E7%A8%8B/" rel="prev" title="MyEclipse 2017/2018 安装与破解 教程">
      <i class="fa fa-chevron-left"></i> MyEclipse 2017/2018 安装与破解 教程
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/03/07/%E5%8F%98%E9%87%8F%E5%92%8C%E7%B1%BB%E5%9E%8B/" rel="next" title="变量和类型">
      变量和类型 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  
   <div>
      
        ﻿
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/">JAVA高效网络库Okhttp3</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 刘正星 的个人博客">刘正星</a></p>
  <p><span>发布时间:</span>2020年03月04日 - 22:03</p>
  <p><span>最后更新:</span>2020年03月04日 - 22:03</p>
  <p><span>原始链接:</span><a href="/blog/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/" title="JAVA高效网络库Okhttp3">https://gitee.com/lzx411559669/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://gitee.com/lzx411559669/2020/03/04/JAVA%E9%AB%98%E6%95%88%E7%BD%91%E7%BB%9C%E5%BA%93Okhttp3/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

      
   </div>
  </div>


          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC80ODg4Ny8yNTM4MQ=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Get同步请求"><span class="nav-number">2.</span> <span class="nav-text">Get同步请求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#get-异步请求"><span class="nav-number">3.</span> <span class="nav-text">get 异步请求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Post-提交表单数据"><span class="nav-number">4.</span> <span class="nav-text">Post 提交表单数据</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实战：爬取北京大学的课表"><span class="nav-number">4.0.1.</span> <span class="nav-text">实战：爬取北京大学的课表</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Headers"><span class="nav-number">5.</span> <span class="nav-text">Headers</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#传送门：HTTP-header文档"><span class="nav-number">5.0.0.1.</span> <span class="nav-text">传送门：HTTP header文档</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#User-Agent"><span class="nav-number">5.1.</span> <span class="nav-text">User-Agent</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Referer"><span class="nav-number">5.2.</span> <span class="nav-text">Referer</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Host"><span class="nav-number">5.3.</span> <span class="nav-text">Host</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#下载文件，图片"><span class="nav-number">6.</span> <span class="nav-text">下载文件，图片</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#写入文本文件："><span class="nav-number">6.0.0.1.</span> <span class="nav-text">写入文本文件：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#写入二进制文件："><span class="nav-number">6.0.0.2.</span> <span class="nav-text">写入二进制文件：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#下载图片：跟二进制文件一致。"><span class="nav-number">6.0.0.3.</span> <span class="nav-text">下载图片：跟二进制文件一致。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#解析excel"><span class="nav-number">6.0.0.4.</span> <span class="nav-text">解析excel</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#cookie-amp-session"><span class="nav-number">7.</span> <span class="nav-text">cookie&amp;session</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#cookie"><span class="nav-number">7.1.</span> <span class="nav-text">cookie</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-前提"><span class="nav-number">7.1.1.</span> <span class="nav-text">1.前提</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-找到cookie"><span class="nav-number">7.1.2.</span> <span class="nav-text">2.找到cookie</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#session"><span class="nav-number">7.2.</span> <span class="nav-text">session</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#收集信息"><span class="nav-number">7.2.1.</span> <span class="nav-text">收集信息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编码实现"><span class="nav-number">7.2.2.</span> <span class="nav-text">编码实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#复用session"><span class="nav-number">7.3.</span> <span class="nav-text">复用session</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#知识点"><span class="nav-number">7.3.1.</span> <span class="nav-text">知识点</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="刘正星"
      src="/blog/uploads/me.jpg">
  <p class="site-author-name" itemprop="name">刘正星</p>
  <div class="site-description" itemprop="description">一名不知名的小菜鸡</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">6</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/lzx411559669" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;lzx411559669"><i class="fa fa-fw fa-gitee"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://github.com/lzx411559669" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lzx411559669" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/blog/411559669@qq.com" title="E-Mail → 411559669@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="http://wpa.qq.com/msgrd?v=3&uin=411559669&site=qq&menu=yes" title="QQ → http:&#x2F;&#x2F;wpa.qq.com&#x2F;msgrd?v&#x3D;3&amp;uin&#x3D;411559669&amp;site&#x3D;qq&amp;menu&#x3D;yes" rel="noopener" target="_blank"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
  </div>



      </div>

     <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=471565537&auto=0&height=66"></iframe>

<!--
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=220 src="//music.163.com/outchain/player?type=0&id=4894835465&auto=0&height=430"></iframe>
-->
<iframe scrolling="no" src="https://tianqiapi.com/api.php?style=tx&skin=sogou" frameborder="0" width="100%" height="50" allowtransparency="true"></iframe>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">刘正星</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">39k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">35 分钟</span>
</div>
<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.2
  </div>
-->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<!--
<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>
  <span class="post-meta-divider">|</span>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共16.2k字</span>
</div>

-->

<span id="busuanzi_container_site_pv" > 总访问量 <span id="busuanzi_value_site_pv"></span> 次 </span>
<span id="busuanzi_container_site_uv" >| 总访客数 <span id="busuanzi_value_site_uv"></span> 人 </span>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">| 博客全站共16.2k字</span>
</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

</body>
</html>
<!-- ��̬���� -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
<!-- ҳ����С���� -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>